// #ifdef APP
var facebook = uni.requireNativePlugin("sn-facebook");
// #endif

import {
	userLogout
} from '@/api/auth.js'

import store from '@/store/index.js'
import gloConfig from '@/config/index.js'
import {
	googleLogin
} from '@/api/auth.js'

/**
 * @private
 * @param {Object} service 获取登录授权对象后可进行登录认证操作
 */
function login(service) {
	return new Promise((resolve, resject) => {
		service.login((e) => {
			console.log("登录认证成功!", e)
			resolve(true)
		}, (e) => {
			plus.nativeUI.alert("登录认证失败: " + JSON.stringify(e));
			resolve(false)
		});
	})
}
/**
 * 获取登录鉴权服务列表，单独保存登录鉴权服务对象
 * 5+APP在plusready事件中调用，uni-app在vue页面的onLoad中调用
 * @param {Object} provider 需要登录的平台
 */
function getService(provider) {
	return new Promise((resolve, resject) => {
		let result = false
		plus.oauth.getServices((services) => {
			console.log("getServices", services)
			for (let i in services) {
				let service = services[i];
				if (service.id == provider) {
					result = service
					break;
				}
			}
			resolve(result)
		}, (err) => {
			console.log('getServicesErr', err)
			resolve(false)
		})
	})
}

async function getUserInfo(service) {
	return new Promise((resolve, resject) => {
		uni.showLoading({
			mask: true
		})
		service.getUserInfo((e) => {
			console.log("获取用户信息成功：", e)
			uni.hideLoading()
			resolve(true)
		}, (e) => {
			uni.hideLoading()
			plus.nativeUI.alert("获取用户信息失败： " + JSON.stringify(e));
			resolve(false)
		})
	})
}


/**
 * 退出登录
 * @param {Object} provider 平台
 */
function authLogout(provider) {
	console.log(provider)
	return new Promise(async (resolve, resject) => {
		let result = await store.dispatch('moduleA/logout')
		// let result = await userLogout()
		console.log(result)
		if (result?.code === 1) {
			// #ifdef APP-PLUS
			if (provider === 'facebook') {
				facebook.logout((e) => {});
			} else if (provider === 'google') {
				let service = await getService(provider)
				service.logout((e) => {}, (e) => {});
			}
			// #endif
			// #ifdef H5
			if (provider === 'facebook') {
				if (window.FB) {
					FB.getLoginStatus((response) => {
						if (response && response.status === 'connected') {
							FB.logout((response) => {});
						} else {}
					});
				} else {
					throw Error('facebook sdk 未加载')
				}
			} else if (provider === 'google') {
				// let service = await getService(provider)
				// service.logout((e) => {
				// 	plus.nativeUI.alert("注销登录认证成功!", (e) => {
				// 		success && success(e)
				// 	});
				// }, (e) => {
				// 	plus.nativeUI.alert("注销登录认证失败: " + JSON.stringify(e));
				// });
			}
			// #endif
			resolve(true)
		}else{
			
			resolve(false)
		}
	})

}

/**
 * 登录
 * @param {Object} provider 平台
 */
async function authLogin(provider) {
	return new Promise(async (resolve, resject) => {
		console.log("provider: ",provider);
		// #ifdef APP-PLUS
		if (provider === 'facebook') {
			let isHoveApp = plus.runtime.isApplicationExist({
				pname: "com.facebook.katana",
				action: "fb://", // iOS需要把fb添加到白名单中
			})
			console.log("isHoveApp: ",isHoveApp);
			if (isHoveApp) {
				facebook.loginWithParams({
					permissions: [
						// 权限，更多权限请看 https://developers.facebook.com/docs/permissions/reference
						"email",
						// "user_photos",
						// "user_gender",
						// "user_birthday",
						"public_profile",
					],
					// 返回字段，更多字段请查看 https://developers.facebook.com/docs/graph-api/reference/user/
					fields: "id, name, email", // gender, birthday,
				}, (e) => {
					console.log("loginWithParams: ",e);
					if (e.result) {
						return resolve(e.data)
					} else {
						return resolve(null)
					}
				});
			} else {
				// plus.nativeUI.alert("当前环境不支持" + provider + "登录");
				return resolve(null)
			}
		} else if (provider === 'google') {
			let service = await getService(provider)
			console.log('service', service)
			if (!service) {
				// plus.nativeUI.alert("当前环境不支持" + provider + "登录");
				return resolve(false);
			}
			if (!service.authResult) {
				let result = await login(service)
				console.log('login', result)
				if (!result) return resolve(false);
			} else {
				console.log("已经登录认证过了!")
			}
			await getUserInfo(service)
			return resolve(service)
		}
		// #endif

		// #ifdef H5
		// 检查用户登录状态
		if (provider === 'facebook') {
			return resolve(await FB_login())
			// checkLoginState(provider)
		} else if (provider === 'google') {
			let googleParams = uni.getStorageSync('oauth2-google-params')
			let params = googleParams && JSON.parse(googleParams);
			if (params && params['access_token']) {
				let xhr = new XMLHttpRequest();
				xhr.open('GET',
					'https://www.googleapis.com/drive/v3/about?fields=user&' +
					'access_token=' + params['access_token']);
				xhr.onreadystatechange = (e) => {
					if (xhr.readyState === 4 && xhr.status === 200) {
						return resolve(JSON.parse(xhr.response))
					} else if (xhr.readyState === 4 && xhr.status === 401) {
						// 令牌无效，因此提示用户权限。
						oauth2SignIn();
					}
				};
				xhr.send(null);
			} else {
				oauth2SignIn();
			}
		} else {
			uni.showToast({
				title: '不支持的登录方式'
			})
			throw Error('不支持的登录方式')
		}
		// #endif
	})
}
/*
 * 创建表单以从Google的OAuth 2.0服务器请求访问令牌。
 */
function oauth2SignIn() {
	let form = document.createElement('form');
	form.setAttribute('method', 'GET'); // 作为GET请求发送。
	form.setAttribute('action', gloConfig.oauth2Endpoint);
	let params = {
		client_id: gloConfig.client_id,
		redirect_uri: gloConfig.redirect_uri,
		oauth2Endpoint: gloConfig.oauth2Endpoint,
		scope: 'email',
		state: 'try_sample_request',
		include_granted_scopes: 'true',
		response_type: 'token'
	};

	// 将表单参数添加为隐藏的输入值。
	for (let p in params) {
		let input = document.createElement('input');
		input.setAttribute('type', 'hidden');
		input.setAttribute('name', p);
		input.setAttribute('value', params[p]);
		form.appendChild(input);
	}
	// 将表单添加到页面并提交以打开OAuth 2.0端点.
	document.body.appendChild(form);
	form.submit();
}

function checkLoginState(provider) { // 当一个人完成登录按钮时调用。
	return new Promise((resolve, resject) => {
		FB.getLoginStatus(async (response) => {
			let result = await FB_login();
			if (!result) return resolve(null)
			return resolve(result)
		});
	})
}

// async function statusChangeCallback(response) { // 使用FB.getLoginStatus的结果调用。
// 	if (response.status === 'connected') { // 已登录您的网页和Facebook。
// 		let result = await FB_api_me(response?.authResponse?.accessToken)
// 		console.log('Successful login for: ', result);
// 		return result
// 	} else { // 未登录您的网页，或者我们无法告知。
// 		let result = await FB_login()
// 		if (!result) return false
// 		return result
// 	}
// }

function FB_login() {
	return new Promise((resolve, resject) => {
		FB.login(async (response) => {
			console.log('login', response)
			if (response.status === 'connected') {
				FB.api('/me?fields=id,name,email', (response1) => {
					console.log('Good to see you, ', response1);

					return resolve({
						...response.authResponse,
						...response1
					})
				});
			} else {
				// uni.showToast({
				// 	title: '未登录您的网页，或者我们无法告知。',
				// 	icon: "error"
				// })
				return resolve(false)
			}
		});
	})
}
/**
 * 为 Facebook 登录功能启用 JavaScript SDK
 */
function integrationLogin() {
	// #ifdef H5
	window.fbAsyncInit = function() {
		FB.init({
			appId: '227365603219143',
			xfbml: true,
			version: 'v16.0'
		});
		FB.AppEvents.logPageView();
	};

	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) {
			return;
		}
		js = d.createElement(s);
		js.id = id;
		js.src = "https://connect.facebook.net/en_US/sdk.js";
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));

	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) {
			return;
		}
		js = d.createElement(s);
		js.id = id;
		// js.onload = initGoogleAuth
		// https://accounts.google.com/gsi/client
		js.src = "https://accounts.google.com/gsi/client";
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'google-jssdk'));

	// #endif


}

function initGoogleAuth() {
	window.google.accounts.oauth2.initTokenClient({
		client_id: gloConfig.client_id,
		scope: 'https://www.googleapis.com/auth/user.gender.read https://www.googleapis.com/auth/user.birthday.read https://www.googleapis.com/auth/userinfo.profile',
		// ux_mode: 'popup',
		callback: (data) => {
			googleCB(data);
		},
		error_callback: (e) => {}
	});
}
export {
	integrationLogin,
	authLogin,
	authLogout
}